import { _decorator, Component, Node, TERRAIN_HEIGHT_BASE, Sprite, Color } from 'cc';
import { audioManager } from '../../ccc3-framework-core/framework/modules/audioManager';
import { BaseObject } from '../../ccc3-framework-core/framework/modules/baseObject';
import dataUtil from '../../ccc3-framework-core/framework/modules/dataUtil';
import eventUtil from '../../ccc3-framework-core/framework/modules/eventUtil';
import { uiManager } from '../../ccc3-framework-core/framework/modules/uiManager';
import { gameState } from '../../ccc3-framework-core/gameState';
import { platformUtil } from '../../ccc3-framework-core/platform/platformUtil';
import Common from '../../ccc3-framework-core/utils/Common';
import { Debug } from '../../ccc3-framework-core/utils/Debug';
import { SpineComponent } from '../../ccc3-framework-core/utils/SpineComponent';
import { BundlesDefine, CategoryDefine, eventDefine, formDefine, pathDefine } from '../CustomDefine';
import { partControl } from './partControl';
import { partHorizontalControl } from './partHorizontalControl';
const { ccclass, property } = _decorator;

@ccclass('mapControl')
export class mapControl extends BaseObject {

    public partHorizontalCtl: partHorizontalControl = null

    @property({ type: Node })
    public editContainer: Node = null;

    @property({ type: Node })
    public btnPlay: Node = null;

    @property({ type: SpineComponent })
    public sp?: SpineComponent;


    @property({
        type: [String]
    })
    public answerArr: string[] = [];
    @property({
        type: [String]
    })
    public startArr: string[] = [];

    @property
    public isIntro: boolean = true;

    private backTimeScale = 4;

    start() {
        this.sp.addCompleteListener((trackEntry) => {
            let aniName = trackEntry.animation.name;
            let answerAniName = this.convertIndexArrToAniName(this.answerArr)
            Debug.log("当前:", aniName, "---正确:", answerAniName);
            //如果是正确的动画
            if (aniName == answerAniName) {
                //过关
                Debug.log("过关");
                audioManager.playAudio("win");
                gameState.instance.gameOver({ isWin: true });
            } else {
                //倒放
                Debug.log("倒放")
                this.setBgGray(true);
                this.sp.backPlayNow(() => { this.backPlayFinish(); }, this.backTimeScale);
                audioManager.playAudio("fail");
                platformUtil.currentPlatform.vibrateLong();
            }

        });
        this.bindTouchEnd(this.btnPlay, () => {
            //播放当前index的动画
            this.playSp(this.getNowIndexArr());
            let finger2 = this.node.getChildByName("finger2");
            finger2 && (finger2.active = false);
        });
    }
    backPlayFinish() {
        this.sp.pause();
        this.showEditUI();
        this.setBgGray(false);
    }
    onLoad() {
        this.partHorizontalCtl = this.editContainer.getComponent(partHorizontalControl);
    }
    onEnable() {
        let finger1 = this.node.getChildByName("finger1");
        finger1 && (finger1.active = true);
        let finger2 = this.node.getChildByName("finger2");
        finger2 && (finger2.active = false);

        //设置part的默认index
        for (let i = 0; i < this.partHorizontalCtl.node.children.length; i++) {
            this.partHorizontalCtl.node.children[i].getComponent(partControl).setStartIndex(this.startArr[i]);
        }
        if (this.isIntro) {
            this.showPlayUI();
            this.playSp(this.startArr);
            this.sp.pause();
            //进入关卡要播放一次默认动画
            this.scheduleOnce(() => {
                this.playSp(this.startArr);
            }, 1)
        } else {
            this.showEditUI();
        }
        this.setBgGray(false);


        platformUtil.currentPlatform.startRecord(300, () => {
            console.log('开始录屏');
        });
    }
    showEditUI() {
        this.editContainer.active = true;
        this.btnPlay.active = true;
        this.sp.node.active = false;
    }
    showPlayUI() {
        this.sp.node.active = true;
        this.editContainer.active = false;
        this.btnPlay.active = false;
    }

    setBgGray(isGray) {
        let bg = this.node.getChildByName("bg");
        bg.children.forEach(element => {
            element.getComponent(Sprite).grayscale = isGray;
        });
        let tx = this.node.getChildByName("tx");
        tx.active = isGray;
        // this.sp.setColor(isGray ? Color.GRAY : Color.WHITE);
        this.node.getChildByName("csm_r").getComponent(Sprite).grayscale = isGray;
        this.node.getChildByName("csm_r2").getComponent(Sprite).grayscale = isGray;
        this.node.getChildByName("csm_l").getComponent(Sprite).grayscale = isGray;
        this.node.getChildByName("csm_l2").getComponent(Sprite).grayscale = isGray;
    }

    playSp(indexArr) {

        let local_fatigue_num = dataUtil.getUnlockNumByDetailId(1, CategoryDefine.FATIGUE);
        if (local_fatigue_num > 0) {
            //扣体力
            dataUtil.addUnlock(1, CategoryDefine.FATIGUE, -1, 1);
            eventUtil.dispatchEvent(eventDefine.FATIGUE_NUM_CHANGED, null);

            this.showPlayUI();
            this.sp.resume();
            let aniName = this.convertIndexArrToAniName(indexArr);
            Debug.log("aniName", aniName)
            this.sp.play(aniName);
        }
        else {
            uiManager.pushUIForm(pathDefine.formDir + formDefine.fatigueForm, null, BundlesDefine.main);
        }

    }

    //获取所有changePartArray的partIndex
    getNowIndexArr() {
        let indexArr = [];
        for (let index = 0; index < this.partHorizontalCtl.node.children.length; index++) {
            let partCtl = this.partHorizontalCtl.node.children[index].getComponent(partControl)
            indexArr.push(this.partHorizontalCtl.isHorizontal ? `${partCtl.posIdx}${partCtl.partIndex}` : `${partCtl.partIndex}`);
        }
        return indexArr;
    }

    //转换indexArr为对应的动画名
    convertIndexArrToAniName(indexArr) {
        let tempArr = [];
        for (let index = 0; index < indexArr.length; index++) {
            let tempStr = indexArr[index];
            if (!this.partHorizontalCtl.isHorizontal) {
                //因为动画名是从1开始的，所以要加1
                tempArr[index] = `${parseInt(tempStr) + 1}`;
                tempArr[index] = this.padLeft(tempArr[index]);
            } else {
                tempArr[index] = `${parseInt(tempStr[0]) + 1}${parseInt(tempStr[1]) + 1}`;
            }
        }
        return tempArr.join("_");
    }
    //左边补0
    padLeft(str) {
        if (str.length < 2) {
            return "0" + str;
        }
        return str;
    }

}

